$(function () {
  // 1,获取标签元素
  let linkReg = document.querySelector('.link-reg');
  let linkRoll = document.querySelector('.link-roll');
  let enter = document.querySelector('.enter');
  let enroll = document.querySelector('.enroll');

  // 点击linkReg, 跳到注册页面
  linkReg.addEventListener('click', function () {
    enter.style.display = 'none';
    enroll.style.display = 'block';
  });
  // 点击linkRoll, 跳到登录页面
  linkRoll.addEventListener('click', function () {
    enter.style.display = 'block';
    enroll.style.display = 'none';
  });

  // layui表单验证
  let form = layui.form;
  form.verify({
    pwd: [/^[a-zA-Z0-9_.-]{6,16}$/, '密码必须是6到16位，且不能出现空格和中文'],
    //检验两次密码是否一致
    repwd: function (value) { //value代表再次输入密码的表单值
      let pwd = document.querySelector('.enroll .opwd');
      if (value !== pwd.value) {
        return '两者密码不一致'
      }
    }
  });

  

  // 注册接口调用
  let username = document.querySelector('.username');
  let pwd = document.querySelector('.opwd');
  let repwd = document.querySelector('.layui-input-inline .repwd');
  $('#form_reg').on('submit', function (e) {
    e.preventDefault(); //阻止默认事件
    $.ajax({
      method: 'POST',
      url: "/api/reg",
      data: {
        username: username.value,
        password: pwd.value,
        repassword: repwd.value,
      },
      success: function (res) {
        if (res.code === 1) {
          return layer.msg(res.message);
        }
        if (res.code !== 0 && res.code !== 1) {
          return layer.msg(res.message);
        }
        layer.msg(res.message + '请登录');
        linkRoll.click();
        console.log(res);
      }
    });
  });

  // 登录接口
  let enName = document.querySelector('.enName');
  let enPass = document.querySelector('.enPass');
  $("#form_enter").on('submit', function (e) {
    e.preventDefault();
    $.ajax({
      method:'POST',
      url: "/api/login",
      data: {username:enName.value,password:enPass.value},
      success: function (res) {
        if(res.code !== 0){
          return layer.msg(res.message)
        };
        layer.msg(res.message);
        // 把登录成功后的token字符串保存到本地
        localStorage.setItem('token',res.token);
        //登录成功后跳转到后台主页
        location.href = '/index.html';
        console.log( localStorage.getItem('token'));
        console.log(res);
      }
    });
  })

});